<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

/**
 * Description of MY_Controller
 *
 * @author Admin
 */
class MY_Controller extends CI_Controller {

	// Mang truyen bien sang view
	public $data;
	// Load config tu csdl
	var $siteConfig;
	// Style hien tai cua trang
	var $style;
	var $user = false;
	var $ajax = false;
	private $inAdminFolder = false;
	var $upload_error;

	function __construct() {
		parent::__construct();
		if (!ini_get('date.timezone')) {
			date_default_timezone_set('Asia/Ho_Chi_Minh');
		}
		$this->load->helper('language');
		$this->load->helper('debug');
		$this->load->helper('user');
		$this->load->helper('global');
		$this->load->helper('cookie');
		$this->load->helper('style');
		$this->load->helper('date');
		$this->load->driver('cache');


		$admin_folder = $this->config->item('admin_folder');

		//Detect ajax request
		$header = $this->input->request_headers();
		if (isset($header['Accept'])) {
			$accept = $header['Accept'];
			if (strpos($accept, 'application/json') !== false)
				$this->ajax = true;
		}

		//Load config
		$this->siteConfig = uconfig_get();
		$this->data['config'] = $this->siteConfig;

		//Load style
		$this->style = style_get($this->siteConfig->style);

		// 
		if ($this->session->userdata('user_id') === FALSE)
			$this->session->set_userdata('user_id', $this->siteConfig->guest_id);
		$this->user = $this->getUserInfo();

		if ($this->session->userdata('viewed') === FALSE)
			$this->session->set_userdata('viewed', array());

		if ($this->session->userdata('voted') === FALSE)
			$this->session->set_userdata('voted', array());

		if ($this->session->userdata('reported') === FALSE)
			$this->session->set_userdata('reported', array());
//		pr($this->uri->segments());die;
		switch ($this->uri->segment(1)) {
			case $admin_folder: {
					$this->inAdminFolder = true;
					if ($this->uri->total_segments() == 1)
						redirect(url_create('admin', 'dashboard'));

					if ($this->uri->segment(2) != 'login') {
						if (!$this->isUserLogin()) {
							redirect($admin_folder . '/login?ref=' . $this->uri->uri_string());
						}
						if (!$this->checkPermission()) {
							if ($this->ajax)
								echo json_encode(array(
									'state' => 'error',
									'title' => lang('error'),
									'message' => lang('not_authentication'),
								));
							else
							if ($this->isUserLogin())
								show_error(lang('not_authentication'));
							else {
								redirect(url_create('admin', 'login', 'index') . '?ref=' . urlencode(site_url($this->uri->uri_string())));
							}
						}
					}


					// Load cac module bang dieu khien
					$this->load->model('model_module');
					$modules = $this->model_module->get_list_hash(array(
						'order' => array('index', 'asc')
							));

					$where = array();
					if (!$this->isRootAdmin())
						$where['active'] = 1;
					$menus = $this->model_module->get_list_hash(array(
						'where' => $where,
						'order' => array('index', 'asc')
							));


					array_to_object($menus);

					//Tick module hien tai va cac module cap  tren
					$curr_controller = $this->uri->segment(2) != '' ? $this->uri->segment(2) : $this->config->item('default_controller');

					$curr_controller_id = $this->model_module->get_id(array('controller' => $curr_controller));

					$breadcrumb = breadcrumb_create($modules, $curr_controller_id);

					$this->data['breadcrumb'] = $breadcrumb;
					$this->data['active_menu_id'] = $curr_controller_id;
					$this->data['menus'] = $menus;
					$this->data['modules'] = $modules;
					break;
				}
			default: {
//				pr($this->uri->segments);die;
					if ($this->uri->total_segments() == 0)
						redirect(url_create('site', 'home'));

					if (!$this->checkPermission()) {

						if ($this->ajax)
							echo json_encode(array(
								'state' => 'error',
								'title' => lang('error'),
								'message' => lang('not_authentication'),
							));
						else
						if ($this->isUserLogin())
							show_error(lang('not_authentication'));
						else {
							redirect(url_create('site', 'account', 'fb_login') . '?ref=' . urlencode(site_url($this->uri->uri_string())));
						}
					}

					$this->data['link_faq'] = $this->siteConfig->link_faq;
					$this->data['link_contact'] = $this->siteConfig->link_contact;
					$this->data['link_terms'] = $this->siteConfig->link_terms;
					$this->data['link_about'] = $this->siteConfig->link_about;
					$this->data['link_facebook'] = $this->siteConfig->link_facebook;
					$this->data['favicon'] = $this->siteConfig->favicon;
					$this->data['fb_app_id'] = $this->config->item('fb_app_id');
					$this->data['fb_namespace'] = $this->config->item('fb_namespace');
					$this->data['social_page'] = $this->siteConfig->social_page;
					$this->data['meta_desc'] = $this->siteConfig->meta_desc;
					$this->data['keywords'] = $this->siteConfig->keywords;
					$this->load->helper('smiley');
					$this->data['is_home'] = false;
				}
		}
//		if($this->user->id==2) $this->updateLikes();
		$this->updateLikes();
		$this->data['isAdmin'] = $this->isAdmin();
		$this->data['image_src'] = $this->siteConfig->fb_image;
		$this->data['isLogin'] = $this->isUserLogin();
		$this->data['site_title'] = $this->siteConfig->site_title;
		$this->data['user'] = $this->user;
		$this->data['page'] = $this->uri->segment(1) . "." . $this->uri->segment(2);
		$this->data['url_styles'] = style_admin();
		//
		//pr($this->session->all_userdata());die();
	}

	protected function isRootAdmin() {
		return in_array($this->user->id, $this->config->item('root_admin'));
	}

	protected function isAdmin() {
		return in_array($this->user->group_id, $this->config->item('admin_group')) || $this->isRootAdmin();
	}

	protected function getUserInfo() {
		$this->load->model('model_user');
		$userId = $this->session->userdata('user_id');
		return $this->model_user->get_info($userId);
	}

	protected function isUserLogin() {
		if ($this->user !== false)
			return ($this->user->id !== $this->siteConfig->guest_id);
		return false;
	}

	protected function checkPermission() {
		if ($this->uri->segment(1) == 'cron')
			return true;
		$this->load->model('model_group');

		$group = $this->model_group->get_info($this->user->group_id);
//		pr($group);die;
		$permissions = json_decode($group->permissions);
		if (!$permissions)
			$permissions = array();
		$uri_string = $this->uri->uri_string();
		$segments = 1;
		if ($this->inAdminFolder) {
			$segments = 2;
			$uri_string = preg_replace('/([^\/]+\/[^\/]+\/[^\/]+)(\/.+)?/i', '$1', $uri_string);
		} else {
			$uri_string = preg_replace('/([^\/]+\/[^\/]+)(\/.+)?/i', '$1', $uri_string);
		}
		if ($this->uri->total_segments() == $segments)
			$uri_string .= '/index';
//		echo $uri_string;die;
//		pr($this->uri->segment_array());die;
		$this->user->upload_text_image = ($this->isRootAdmin() || $group->upload_text_image == 1) ? TRUE : FALSE;
		return ($this->isRootAdmin() || in_array($uri_string, $permissions));
	}

	protected function loadView() {
		$this->load->view($this->style->folder . '/' . $this->config->item('layout_file'), $this->data);
	}

	/**
	 * Upload anh len server
	 * @param $image_var
	 * @return stdClass
	 */
	protected function uploadImage($image_var) {
		$config = image_get_upload_config($this->siteConfig);
		$this->load->library('upload', $config);
		if (!$this->upload->do_upload($image_var)) {
			$this->upload_error = $this->upload->display_errors();
//			die();
			return false;
		}
		// Upload va resize
		$upload_data = $this->upload->data();
		
		$resize_config = array(
			'source_image' => $upload_data['full_path'],
			//'create_thumb'	=> TRUE,
			'maintain_ratio' => TRUE,
			'width' => $this->siteConfig->image_width,
			'height' => $this->siteConfig->image_height,
		);
		
		$this->load->library('image_lib', $resize_config);
		$size = getimagesize($upload_data['full_path']);
		if($size[0]>$this->siteConfig->image_width)
			$this->image_lib->resize();
//		if($this->isRootAdmin()){
		$resize_config['wm_type'] = 'overlay';
		$resize_config['wm_vrt_alignment']='top';
		$resize_config['wm_hor_alignment'] = 'right';
		$resize_config['wm_overlay_path'] = $this->siteConfig->wm_overlay_path;
		$resize_config['wm_opacity'] = $this->siteConfig->wm_opacity;
		$resize_config['wm_x_transp'] = $this->siteConfig->wm_x_transp;
		$resize_config['wm_y_transp'] = $this->siteConfig->wm_y_transp;
		
		$this->load->library('image_lib', $resize_config, 'image_lib4');
		$this->image_lib4->watermark();
//		}

		$resize_config['height'] = $this->siteConfig->thumb_height;
		$resize_config['width'] = $this->siteConfig->thumb_width;
		$resize_config['create_thumb'] = TRUE;
		$this->load->library('image_lib', $resize_config, 'image_lib1');
		$this->image_lib1->resize();



		$result = new stdClass();
		$result->path = $config['upload_path'] . '/' . $upload_data['file_name'];
		$result->thumb = preg_replace('/(.+)(\.(' . $this->siteConfig->image_types . '))/i', '$1_thumb$2', $result->path);
		$resize_config['width'] = $this->siteConfig->thumb2_width;
		$resize_config['thumb_marker'] = '_thumb2';
		$this->load->library('image_lib', $resize_config, 'image_lib2');
		$this->image_lib2->resize();


		$result->thumb2 = preg_replace('/(.+)(\.(' . $this->siteConfig->image_types . '))/i', '$1_thumb2$2', $result->path);

		$thumb2_size = getimagesize($result->thumb2);

		if ($thumb2_size[1] > $this->siteConfig->thumb2_height) {
			$resize_config['maintain_ratio'] = FALSE;
			$resize_config['source_image'] = $result->thumb2;
			$resize_config['height'] = $this->siteConfig->thumb2_height;
			$resize_config['create_thumb'] = FALSE;
			$resize_config['x_axis'] = 0;
			$resize_config['y_axis'] = (int) ($thumb2_size[1] - $this->siteConfig->thumb2_height) / 2;
			$this->load->library('image_lib', $resize_config, 'image_lib3');

			if (!$this->image_lib3->crop()) {
				
			}
		}
		return $result;
	}

	protected function reCreateThumb2($path) {
		$thumb2 = preg_replace('/(.+)(\.(' . $this->siteConfig->image_types . '))/i', '$1_thumb2$2', $path);
		@unlink($thumb2);

		$resize_config = array(
			'source_image' => $path,
			'maintain_ratio' => TRUE,
		);
		$resize_config['width'] = $this->siteConfig->thumb2_width;
		$resize_config['height'] = $this->siteConfig->thumb_height;
		$resize_config['thumb_marker'] = '_thumb2';
		$resize_config['create_thumb'] = TRUE;
		$this->load->library('image_lib', $resize_config, 'image_lib2');
		$this->image_lib2->resize();

		$thumb2_size = getimagesize($thumb2);

		if ($thumb2_size[1] > $this->siteConfig->thumb2_height) {
			$resize_config['maintain_ratio'] = FALSE;
			$resize_config['source_image'] = $thumb2;
			$resize_config['height'] = $this->siteConfig->thumb2_height;
			$resize_config['create_thumb'] = FALSE;
			$resize_config['x_axis'] = 0;
			$resize_config['y_axis'] = (int) ($thumb2_size[1] - $this->siteConfig->thumb2_height) / 2;
			$this->load->library('image_lib', $resize_config, 'image_lib3');

			if (!$this->image_lib3->crop()) {
				
			}
		}
	}

	protected function deleteImage($path) {
//		$thumb = preg_replace('/(.+)(\.(' . $this->siteConfig->image_types . '))/i', '$1_thumb$2', $path);
//		$thumb2 = preg_replace('/(.+)(\.(' . $this->siteConfig->image_types . '))/i', '$1_thumb2$2', $path);
//
//		unlink($thumb2);
//		unlink($thumb);
		unlink($path);
	}

	protected function getTopUser($freq, $limit = '') {
		if ($freq != 'month' && $freq != 'week')
			$freq = 'likes';
		if (!is_numeric($limit))
			$limit = $this->siteConfig->right_top_users;
		$topUsers = $this->model_user->get_list(array(
			'where' => array(
				'active' => 1
			),
			'limit' => array(0, $limit),
			'order' => array($freq, 'desc'),
				));

		return $topUsers;
	}

	protected function validation_run() {
		$this->data['errors'] = array();
		if ($this->form_validation->run()) {
			return TRUE;
		}
		foreach ($this->form_validation->_field_data as $param => $val) {
			$this->data['errors'][$param] = form_error($param);
		}
		$this->data['error_message'] = form_error_message($this->form_validation->_field_data);
		return FALSE;
	}

	private function updateLikes(){
		$users = $this->model_user->get_list(array(
			'where'=>array('id >'=>$this->siteConfig->last_updated_id),
			'limit'=>array(0,1),
			'order'=>array('id','asc')
		));
		if(count($users)>0){
			$user = $users[0];
			$this->load->model('model_image');
			$this->model_image->get_total_likes($user->id);
			$this->model_user->update($user->id,array(
				'likes'	=> $this->model_image->get_total_likes($user->id)
			));
			$this->model_config->update(array(
				'last_updated_id'	=> $user->id
			));
		}
		else
		{
			$this->model_config->update(array(
				'last_updated_id'	=> 0
			));
		}
	}
}

?>
